﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using RestSharp;
using Steeltoe.Common.Discovery;
using Steeltoe.Discovery;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Auto.AlgsAndPush.Services
{
    public class HttpClientService
    {
        private readonly DiscoveryHttpClientHandler _handler;

        public HttpClientService(IDiscoveryClient client)
        {
            _handler = new DiscoveryHttpClientHandler(client);
        }
        private HttpClient GetClient()
        {
            return new HttpClient(_handler, false);
        }

        public async Task<HttpResponseMessage> GetAsync(string url)
        {
            var res = await GetClient().GetAsync(url);
            return res;
        }

        public async Task<HttpResponseMessage> PostAsync(string url, object postBody)
        {
            var postStr = JsonConvert.SerializeObject(postBody, 
                new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() });
            var httpRestMsg = new HttpRequestMessage(HttpMethod.Post, url);
            var content = new StringContent(postStr, Encoding.UTF8, "application/json");
            httpRestMsg.Content = content;
            var response = await GetClient().SendAsync(httpRestMsg);
            return response;
        }

        public IRestResponse GetByRest(string url)
        {
            var client = new RestClient(url);
            var request = new RestRequest(Method.GET);
            IRestResponse response = client.Execute(request);
            return response;

        }
        public IRestResponse PostByRest(string url, object postBody)
        {
            var client = new RestClient(url);
            var request = new RestRequest(Method.POST);
            request.RequestFormat = DataFormat.Json;
            var jsonBody = JsonConvert.SerializeObject(postBody);
            request.AddJsonBody(jsonBody);
            IRestResponse response = client.Execute(request);
            return response;
        }
    }
}
